# bullet.py
import pygame
from settings import *

# 使用向量进行精确的数学计算
vec = pygame.math.Vector2

class Bullet(pygame.sprite.Sprite):
    def __init__(self, game, pos, direction):
        super().__init__()
        self.game = game
        self.image = pygame.Surface((BULLET_SIZE, BULLET_SIZE))
        self.image.fill(BULLET_COLOR)
        self.rect = self.image.get_rect()
        self.pos = vec(pos)
        self.rect.center = pos
        self.vel = direction * BULLET_SPEED
        self.spawn_time = pygame.time.get_ticks()

    def update(self):
        self.pos += self.vel * self.game.dt
        self.rect.center = self.pos
        # 如果子弹飞出屏幕或超过生命周期，则销毁
        if not self.game.screen.get_rect().colliderect(self.rect):
            self.kill()
        if pygame.time.get_ticks() - self.spawn_time > BULLET_LIFETIME:
            self.kill()